package org.jtzc.springaiagent.agent.chain;

import org.jtzc.springaiagent.agent.BaseAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wu chuang
 * @description
 */
@Service
public class ChainedAgent implements BaseAgent {

    private final List<BaseAgent> agents;

    @Autowired
    public ChainedAgent(
            @Qualifier("spellingCheckerAgent") BaseAgent spellingChecker,
            @Qualifier("sentimentAnalyzerAgent") BaseAgent sentimentAnalyzer,
            @Qualifier("responseGeneratorAgent") BaseAgent responseGenerator) {

        this.agents = List.of(spellingChecker, sentimentAnalyzer, responseGenerator);
    }

    @Override
    public AgentResponse execute(AgentRequest request) {
        AgentResponse currentResponse = null;
        AgentRequest currentRequest = request;

        for (BaseAgent agent : agents) {
            System.out.println("======================================="+currentRequest);
            currentResponse = agent.execute(currentRequest);
            currentRequest = new AgentRequest(
                    currentResponse.content(),
                    mergeContexts(currentRequest.context(), currentResponse.metadata())
            );
        }

        return currentResponse;
    }

    private Map<String, Object> mergeContexts(
            Map<String, Object> original,
            Map<String, Object> additions) {

        Map<String, Object> merged = new HashMap<>(original);
        merged.putAll(additions);
        return merged;
    }

}
